package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.DateUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lichengming on 2017/6/8.
 */
public class UserController extends Controller {
    //角色对应关系Map
    private static Map<String, String> roleMap = new HashMap<String, String>();

    static {
        roleMap.put("1", "消费者");
        roleMap.put("2", "消费商");
        roleMap.put("3", "商家");
        roleMap.put("4", "品牌合作伙伴");
        roleMap.put("5", "品牌服务中心");
    }

    public void index() {
        renderJsp("/page/user/user_list.jsp");
    }

    public void pagination() {

        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");


        String selectSQL = "select u.*,ua.balance,ua.score ";

        StringBuilder sqlExceptSql = new StringBuilder(" from user u inner join user_account ua on u.id = ua.user_id ");
        List<Object> params = new ArrayList<Object>();

        String nickName = getPara("nick_name", "");
        if (StringUtil.isNotEmpty(nickName.trim())) {
            sqlExceptSql.append(" and u.nick_name like ?");
            params.add("%" + nickName.trim() + "%");
        }

        String phone = getPara("phone");
        if (StringUtil.isNotEmpty(phone)) {
            sqlExceptSql.append(" and u.phone like ?");
            params.add('%' + phone.trim() + "%");
        }

        Integer status = getParaToInt("status");
        if (status != null ) {
            sqlExceptSql.append(" and u.status = ?");
            params.add(status);
        }

        sqlExceptSql.append(" order by u.update_time desc");

        Page<Record> recordList = Db.paginate(pageNumber, pageSize, selectSQL, sqlExceptSql.toString(), params.toArray());

        if(CollectionUtil.isNotEmpty(recordList.getList())){

            //将role的数字字符串转换为文字字符串
            for (Record record : recordList.getList()) {
                String newStr = "";
                String oldStr = record.getStr("role");
                if (StringUtil.isNotEmpty(oldStr)) {
                    for (String str : oldStr.split(",")) {
                        newStr = newStr + roleMap.get(str) + ",";
                    }
                    record.set("role", newStr.substring(0, newStr.length() - 1));
                }
            }

        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void edit() {
        renderJsp("/page/user/user_add.jsp");
    }

    public void save() {

        String name = getPara("name");
        String email = getPara("email");
        int age = getParaToInt("age");

        Record record = new Record();
        record.set("name", name).set("age", age).set("email", email);
        Db.save("user", record);

        renderJson();
    }

    @Before(Tx.class)
    public void customer() {

        String userId = getPara("userId");
        Record record = Db.findFirst("SELECT * FROM `system_param` where `key` = ? and status = 1","custom_user_id");
        if(record == null){
            record.set("key","custom_user_id").set("value",userId)
                .set("update_time", DateUtil.getDate()).set("to_client","0")
                    .set("create_time", DateUtil.getDate())
                    .set("status",1).set("name","客服").set("remark","客服");
            Db.save("system_param", record);
        }else{
            record.set("value",userId).set("update_time", DateUtil.getDate());
            Db.update("system_param", record);
        }

        renderJson(new JsonResult().status("000").show("保存成功"));
    }

    public void customerInfo(){

        String userId = getPara("userId");
        Record user = Db.findById("user",userId);
        setAttr("user",user);

        renderJsp("/page/user/info.jsp");

    }

}
